use calamine::{open_workbook, Reader, Xlsx, Data};
use std::fs::read_dir;
use std::path::{Path, PathBuf};


pub fn read_excel<P: AsRef<Path>>(path: P) -> Result<(), Box<dyn std::error::Error>> {
    // 打开 Excel 文件
    let mut workbook: Xlsx<_> = open_workbook(path)?;

    // 获取所有工作表名称
    let sheet_names = workbook.sheet_names();

    // 遍历每个工作表
    for sheet_name in &sheet_names {
        println!("\n=== 正在处理工作表: {} ===", sheet_name);

        // 修改为：
        match workbook.worksheet_range(sheet_name) {
            Ok(sheet) => {
                // 遍历行数据
                for (row_num, row) in sheet.rows().enumerate() {
                    print!("行{}: ", row_num + 1);
                    for cell in row {
                        // 单元格处理逻辑保持不变
                        match cell {
                            Data::String(s) => print!("{}\t", s),
                            Data::Float(f) => print!("{:.2}\t", f),
                            Data::Int(i) => print!("{}\t", i),
                            Data::Bool(b) => print!("{}\t", b),
                            Data::Empty => print!("[空]\t"),
                            _ => print!("未知类型\t"),
                        }
                    }
                    println!();
                }
            },
            Err(e) => eprintln!("工作表 {} 读取失败: {}", sheet_name, e),
        }
    }
    Ok(())
}

// 判断是否为Excel文件
fn is_excel_file(path: &Path) -> bool {
    path.extension()
        .and_then(|s| s.to_str())
        .map(|ext| {
            let ext_lower = ext.to_lowercase();
            ext_lower == "xlsx" || ext_lower == "xls" || ext_lower == "xlsb" || ext_lower == "ods"
        })
        .unwrap_or(false)
}

// 获取目录下所有Excel文件路径
fn get_excel_files<P: AsRef<Path>>(
    dir_path: P,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    let mut files = Vec::new();

    for entry in read_dir(dir_path)? {
        let entry = entry?;
        let path = entry.path();

        if path.is_file() && is_excel_file(&path) {
            files.push(path);
        }
    }

    Ok(files)
}

pub fn main() {
    let dir_path = "./data/";
    // 获取目录下所有 Excel 文件路径
    let excel_files = get_excel_files(dir_path)
        .unwrap_or_else(|e| {
            eprintln!("目录读取失败: {}", e);
            std::process::exit(1);
        });
    // 遍历处理每个文件
    for file_path in excel_files {
        println!("\n正在处理文件: {}", file_path.display());
        if let Err(e) = read_excel(&file_path) {
            eprintln!("文件处理失败: {}", e);
        }
    }
}
